import React from "react";
// import BaseScreen from "../../BaseScreen";
import ProgressView from "../../../view/ProgressView";
// import { Actions, NameSpace } from "../../../model/taskModel";
// import { connect } from "react-redux";
import styles from "../../../css/attendance.module.css";
import { locationTo } from "../../../utils/LocationUtil";
import * as locations from '../../../const/locations'
// import { MyButton } from "../../../view/MyButton";
import Config from "../../../Config";
import PressTouch from '../../../view/PressTouch'
import { formatTime } from '../../../utils/CommomUtil';
import { attendParams, doCard } from '../../../service/AttendService'
import { getTOKEN } from "../../../utils/StorageUtil";
// import { ADDRGETNETWORKPARAMS } from "dns";
var map, geolocation;
let a = 0
class PunchItem2 extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      GeoLocation: null
    };
    this.timer = null
    this.dakaScope = 0;
    this.daka_addr = '当前不在考勤范围'
    this.isClick = false
  }
  componentWillMount() {
    this.count()

  }
  componentDidMount() {
    this.getLocation()

  }
  componentWillUnmount() {
    a = 0
    clearInterval(this.timer)
  }
  attendParams = () => {
    this.props.setLoading(true)
    attendParams({
      token: getTOKEN()
    })
      .then(
        res => {
          this.props.setLoading(false)
          if (res.error_code === 0) {
            this.isClockScope(res.data)
            this.setState(
              res.data
            )
          }
        }
      )
      .catch(
        err => {
          console.log(err)
        }
      )
  }
  isClockScope = ({ address_data, com_conf, wifi_data }) => {
    const GeoLocation = this.state.GeoLocation
    for (let i = 0; i < address_data.length; i++) {
      const arr = address_data[i].latitude_and_longitude.split(',');
      address_data[i].lat = arr[1]
      address_data[i].lng = arr[0]
      address_data[i].len = Math.sqrt(Math.pow((address_data[i].lat - GeoLocation.lat), 2) + Math.pow((address_data[i].lng - GeoLocation.lng), 2)) * (Math.pow(10, 8) / 90)
      if (address_data[i].len <= com_conf.card_address_range) {
        this.dakaScope = 1;
        this.daka_addr = address_data[i].detail_address
      }
    }
    this.isClick = true
    this.setState({
      dakaScope: this.dakaScope,
      daka_addr: this.daka_addr,
    })
  }
  // 计时
  count = () => {
    const that = this
    this.timer = setInterval(function () {
      const date = new Date()
      that.setState({
        nowTime: formatTime(date.getHours()) + ':' + formatTime(date.getMinutes()) + ':' + formatTime(date.getSeconds())
      })
    }, 1000)
  }
  getLocation = () => {
    a = 1
    const that = this
    //加载地图，调用浏览器定位服务
    map = new window.AMap.Map(this.refs.map2, {
      resizeEnable: true,
      zoom: 8,
    });
    map.plugin('AMap.Geolocation', function () {
      geolocation = new window.AMap.Geolocation({
        enableHighAccuracy: true,//是否使用高精度定位，默认:true
        timeout: 10000,          //超过10秒后停止定位，默认：无穷大
        buttonOffset: new window.AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
        zoomToAccuracy: true,      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
        buttonPosition: 'RB'
      });
      map.addControl(geolocation);
      geolocation.getCurrentPosition();
      window.AMap.event.addListener(geolocation, 'complete', onComplete);//返回定位信息
      window.AMap.event.addListener(geolocation, 'error', onError);      //返回定位出错信息
    });
    //解析定位结果
    function onComplete(data) {
      let str = {}
      str.lng = data.position.lng
      str.lat = data.position.lat
      str.accuracy = data.accuracy
      str.isConverted = data.isConverted
      str.addr = data.formattedAddress
      // 获取打卡范围
      that.attendParams()

      if (a === 1) {
        that.setState({
          GeoLocation: str
        })
      }

    }
    //解析定位错误信息
    function onError(data) {
    }
  }
  
  onClick = () => {
    console.log(this.state)
    if( this.isClick ){
      const {lat,lng,addr} = this.state.GeoLocation
      const { dakaScope,daka_addr} = this.state
      clearInterval(this.timer)
      // 打卡
      const params = {
        token: getTOKEN(),
        card_address: dakaScope === 1?daka_addr:addr,
        coordinate:lat+','+lng,
        is_outside: dakaScope,
      }
  
      doCard(params)
        .then(
          res => {
            this.props.setLoading(false)
  
            if (res.error_code === 0) {
              this.props.reload()
            }
          }
        )
        .catch(
          err => {
            console.log(err)
          }
        )
    }
    
  }
  render() {
    const { type } = this.props
    const { GeoLocation, dakaScope } = this.state
    return (
      <div className={styles['punch']}>
        <PressTouch
          style={{ 
            ...punchCircle, 
            background: dakaScope ? 
            'linear-gradient(to bottom, #7fb2ff, #498eff)' :
            'linear-gradient(to bottom, #cf80ee, #ba74ed)',
            boxShadow:'0 0 50px -10px'+ (dakaScope?Config.BaseColor : '#cc79ed')
           }}
          onClick={this.onClick}
        >
          <div className={styles['punch_title']}>
            {GeoLocation ?
              <span> {type === 'start' ? '上班' : '下班'}打卡</span>
              : '定位中'}
          </div>
          {GeoLocation &&
            <div className={styles['punch_nowtime']}>
              {this.state.nowTime}
            </div>
          }
        </PressTouch>

        {GeoLocation &&
          <div className={styles['punch_isInCircle']}>
            {this.state.daka_addr}
          </div>
        }
        <div ref='map2'></div>
      </div>
    )
  }
}
const punchCircle = {
  width: '120px',
  height: '120px',
  // background: '#cc79ed',
  borderRadius: '50%',
  display: 'flex',
  flexDirection: ' column',
  alignItems: 'center',
  justifyContent: 'center',
  color: '#fff',
  // boxShadow: '0 0 50px 0 #ffffff inset',
  marginBottom: '20px',
}
// const mapStateToProps = state => {
//   return {
//     ...state[NameSpace]
//   };
// };

// const mapDispatchToProps = dispatch => {
//   return {
//     setInfo(Banci) {
//       let params = {
//         Banci: Banci,
//       };
//       dispatch(Actions.actionSelectBanci(params));
//     }
//   };
// };

// export default connect(mapStateToProps, mapDispatchToProps)(PunchItem2);
export default PunchItem2
